package com.logistics.interceptors;

import com.logistics.utils.JwtUtil;
import com.logistics.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌获取
        //每一个页面请求头中都会携带token,具有token则放行

        String token = request.getHeader("Authorization");
        try {
            //检验token（不报错)
            Map<String, Object> claims = JwtUtil.parseToken(token);//获得业务数据
            //将业务数据存放到ThreadLocal中,注意claims为Map
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
